package com.edgar.fileupload.library;

import android.content.Context;
import android.content.Intent;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 文件上传管理类.
 * @author edgar
 */
public class UploadFileManager {
	
	private final LinkedList<FileUploadTask> mUploadTasks = new LinkedList<FileUploadTask>();
	private Context mContext;
	private static UploadFileManager sInstance = new UploadFileManager();
	public static UploadFileManager getInstance(){
		return sInstance;
	}

	public void init(Context context){
		this.mContext = context;
	}

	/**
	 * 文件上传
	 * @param url
	 * @param filePath
	 * @param headerMap 头部参数
	 * @param uploadListener 上传事件
	 */
	public void uploadFile(String url,String filePath, Map<String,String> headerMap,OnUploadListener uploadListener){
		checkUrlValid(url);
		if(filePath != null && filePath.length() > 0){
			uploadFile(url, new File(filePath), headerMap,uploadListener);
		} else {
			notifyUploadFailed(uploadListener, filePath);
		}
	}

	public void uploadMultiFile(String url,List<File> files, Map<String,String> headerMap,OnUploadListener uploadListener){
		checkUrlValid(url);
		if(files != null && files.size() > 0){
			uploadFile(url, files, headerMap,uploadListener);
		}
	}

	public void uploadFile(String url,File uploadFile,  Map<String,String> headerMap,OnUploadListener uploadListener){
		checkUrlValid(url);
		if(uploadFile == null){
			throw new IllegalArgumentException("File cannot null.");
		}
		if(!uploadFile.exists()){
			notifyUploadFailed(uploadListener, uploadFile.getName());
		} else {
			List<File> fileList = new ArrayList<>();
			fileList.add(uploadFile);
			uploadFile(url,fileList,headerMap,uploadListener);
		}
	}

	private void uploadFile(String url,List<File> files,  Map<String,String> headerMap,OnUploadListener listener){
		synchronized (mUploadTasks){
			if(mUploadTasks.isEmpty()){
				startUploadService();
			}
			UploadRequest uploadRequest =
					UploadRequest.createUploadRequest(url, files,headerMap,listener);
			mUploadTasks.add(new FileUploadTask(uploadRequest));
		}
	}

	public FileUploadTask popUploadTask(){
		synchronized (mUploadTasks){
			if(mUploadTasks.isEmpty()){
				return null;
			}
			return mUploadTasks.remove();
		}
	}

	/**
	 * Need check url is valid.
	 * @param url
	 */
	private void checkUrlValid(String url){
		if(url == null || url.length() == 0){
			throw new IllegalArgumentException("url is null");
		}
		if(!url.startsWith("http")){
			throw new IllegalArgumentException("url invalid:"+url);
		}
	}

	private void startUploadService(){
		Intent intent = new Intent(mContext,FileUploadService.class);
		mContext.startService(intent);
	}

	public void notifyUploadFailed(OnUploadListener listener,String fileName){
		if(listener != null){
			listener.onUploadFailed(fileName);
		}
	}
}